"""
12306查票程序

模块：
    requests >>> pip install requests
    pandas   >>> pip install pandas

1 数据来源
    需求：输入出发地 - 目的地 时间 实现查票的功能
"""
import requests

url = 'https://kyfw.12306.cn/otn/leftTicket/query'

params = {
    'leftTicketDTO.train_date': '2022-08-01',
    'leftTicketDTO.from_station': 'LVJ',
    'leftTicketDTO.to_station': 'TJP',
    'purpose_codes': 'ADULT'
}

headers = {

    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/54.0.2840.99 Safari/537.36 "
}

cookies = {
    'Cookie': '_uab_collina=165934111986773422040509; JSESSIONID=E8716EC1AD0E6FF1245012EA8D04D2F7; BIGipServerotn=1206911498.38945.0000; BIGipServerpool_passport=182714890.50215.0000; RAIL_EXPIRATION=1659660405187; RAIL_DEVICEID=Ngi702I8pd79qDTwdE6iWHmOClSX3E54_seO6k_aIsBT4B_OmzGJ3RNm6vF2Z-DPDgKlRp4rGA47X55B1P-tsf7wtdTrLmzdtgVczq9I8LFUpr7AXJDy8KFI2SV4czPUnntZVIC7R-2XCpwJwgcbHltBvPPwD6ub; guidesStatus=off; highContrastMode=defaltMode; cursorStatus=off; route=6f50b51faa11b987e576cdb301e545c4; _jc_save_fromStation=%u5170%u5DDE%u4E1C%2CLVJ; _jc_save_toStation=%u5929%u6D25%2CTJP; _jc_save_fromDate=2022-08-01; _jc_save_toDate=2022-08-01; _jc_save_wfdc_flag=dc'
}
response = requests.get(url=url, params=params, headers=headers, cookies=cookies)
response.encoding = response.apparent_encoding   # 自动识别编码
result = response.json()['data']['result']

# 解析数据
for index in result:
    index_list = index.split('|')   # 字符串分割
    num = index_list[3]  # 车次
    if 'G' in num:
        start = index_list[8]  # 发车时间
        end = index_list[9]  # 到站时间
        userTime = index_list[10]  # 耗时
        top = index_list[32]  # 特等座
        first = index_list[31]  # 一等座
        second = index_list[30]  # 二等座
        dict = {
            'Num': num,
            'start': start,
            'end': end,
            'userTime': userTime,
            'top': top,
            'first': first,
            'second': second,
        }
    else:
        start = index_list[8]  # 发车时间
        end = index_list[9]  # 到站时间
        userTime = index_list[10]  # 耗时
        RW = index_list[23]  # 软卧
        YW = index_list[28]  # 硬卧
        YZ = index_list[29]  # 硬座
        WZ = index_list[26]  # 无座
        dict = {
            'Num': num,
            'start': start,
            'end': end,
            'userTime': userTime,
            'RW': RW,
            'YW': YW,
            'YZ': YZ,
            'WZ': WZ,
        }

    print(dict)
